<template>
  <el-dialog
    :title="isEdit ? '编辑培养层次' : '新增培养层次'"
    v-model="visible"
    width="400px"
    @closed="handleClosed"
  >
    <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
      <el-form-item label="层次名称" prop="name">
        <el-input v-model="form.name" placeholder="请输入层次名称"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { ref, computed, watch, nextTick } from 'vue';

export default {
  name: 'TrainingLevelDialog',
  props: {
    modelValue: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({}) },
    submitting: { type: Boolean, default: false }
  },
  emits: ['update:modelValue', 'submit', 'cancel'],
  setup(props, { emit }) {
    const formRef = ref(null);
    
    const visible = computed({
      get: () => props.modelValue,
      set: (value) => emit('update:modelValue', value)
    });
    
    const form = ref({
      id: null,
      name: ''
    });
    
    const isEdit = computed(() => !!form.value.id);
    
    const rules = {
      name: [
        { required: true, message: '请输入层次名称', trigger: 'blur' }
      ]
    };
    
    watch(() => props.formData, (newData) => {
      if (newData) {
        form.value = { ...newData };
      }
    }, { immediate: true, deep: true });
    
    const handleSubmit = async () => {
      if (!formRef.value) return;
      
      try {
        await formRef.value.validate();
        emit('submit', form.value);
      } catch (error) {
        console.error('表单验证失败:', error);
      }
    };
    
    const handleCancel = () => {
      emit('cancel');
    };
    
    const handleClosed = async () => {
      // 强制重置表单数据
      form.value.id = null;
      form.value.name = '';
      
      await nextTick();
      if (formRef.value) {
        formRef.value.clearValidate();
      }
    };
    
    return {
      formRef,
      visible,
      form,
      isEdit,
      rules,
      handleSubmit,
      handleCancel,
      handleClosed
    };
  }
};
</script>

<style scoped>
:deep(.el-dialog__body) {
  padding-top: 10px;
}

:deep(.el-dialog__footer) {
  padding-top: 0;
}

/* 强制设置对话框宽度 */
:deep(.el-dialog) {
  width: 400px !important;
  max-width: 400px !important;
  min-width: 400px !important;
}
</style>